package com.ueboot.weishop.admin.batch.tasklet;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.ueboot.core.utils.DateUtils;
import com.ueboot.weishop.entity.activity.ActivityAttrEntity;
import com.ueboot.weishop.entity.activity.CrowResultEntity;
import com.ueboot.weishop.entity.lottery.LotteryRecordEntity;
import com.ueboot.weishop.entity.order.OrderEntity;
import com.ueboot.weishop.entity.order.OrderEnum;
import com.ueboot.weishop.entity.order.OrderExtensionEntity;
import com.ueboot.weishop.entity.order.OrderIssueEntity;
import com.ueboot.weishop.service.activity.ActivityAttrService;
import com.ueboot.weishop.service.activity.CrowResultService;
import com.ueboot.weishop.service.lottery.LotteryRecordService;
import com.ueboot.weishop.service.order.OrderExtensionService;
import com.ueboot.weishop.service.order.OrderIssueService;
import com.ueboot.weishop.service.order.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SendDmsStepSecondTasklet implements Tasklet {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private OrderService orderService;

	@Autowired
	private OrderIssueService issueService;

	@Autowired
	private LotteryRecordService lotteryRecordService;

	@Autowired
	private ActivityAttrService attrService;

	@Autowired
	private OrderExtensionService extensionService;

	@Autowired
	private CrowResultService crowResultService;

	@Override
	public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
		String batchNo = DateUtils.getCurrentDateTime();
		List<OrderEntity> orderList = orderService.findByExtStatusAndOrderStatus(OrderEnum.EXT_STATUS_1, OrderEnum.ORDER_STATUS_2);
		List<LotteryRecordEntity> lotteryRecordList = lotteryRecordService.findByExtStatus(OrderEnum.EXT_STATUS_1);
		List<CrowResultEntity> crowResultList = crowResultService.findByIssueDms(CrowResultEntity.ISSUE_DMS_2);
		if (orderList.size() < 1 && lotteryRecordList.size() < 1 && crowResultList.size() < 1) {
			logger.info("下发DMS优惠券跑批任务 step second 本次无发送DMS代金券数据......数据条数为0条");
			return RepeatStatus.FINISHED;
		}

		List<OrderIssueEntity> issueList = Lists.newLinkedList();
		issueList.addAll(this.convertCrowResultToDmsModel(crowResultList, batchNo));
		issueList.addAll(this.convertOrderToDmsModel(orderList, batchNo));
		issueList.addAll(this.convertLotteryToDmsModel(lotteryRecordList, batchNo));
		issueService.saveIssueUpdateOrderAndLottery(issueList, lotteryRecordList, orderList);
		logger.info("下发DMS优惠券跑批任务 step second 本批次下发总量为{}......抽奖转换数量：{}，订单转换数量：{}", issueList.size(), lotteryRecordList.size(), orderList.size());
		return RepeatStatus.FINISHED;
	}

	private List<OrderIssueEntity> convertOrderToDmsModel(List<OrderEntity> orderList, String batchNo) {

		List<OrderIssueEntity> issueList = Lists.newLinkedList();
		orderList.forEach(order -> {
			OrderIssueEntity issue = new OrderIssueEntity();
			OrderExtensionEntity orderExtension = extensionService.findByOrderNo(order.getOrderNo());
			List<ActivityAttrEntity> activityAttrList = attrService.findBySn(order.getActivitySN());
			logger.info(JSON.toJSONString(activityAttrList));
			activityAttrList.forEach(attr -> {
				if ("campaignCode".equalsIgnoreCase(attr.getKeyName())) {
					issue.setCampaignCode(attr.getValue());
				} else if ("validBeginDate".equalsIgnoreCase(attr.getKeyName())) {
					issue.setValidBeginDate(attr.getValue());
				} else if ("validEndDate".equalsIgnoreCase(attr.getKeyName())) {
					issue.setValidEndDate(attr.getValue());
				} else if ("amount".equalsIgnoreCase(attr.getKeyName())) {
					String amount = (Integer.valueOf(attr.getValue()) * order.getPayAmount()) / 100 + "";
					issue.setAmount(amount);
					issue.setLimitDeduct(amount);
				} else if ("amountDiscount".equalsIgnoreCase(attr.getKeyName())) {
					String amountDiscount = (order.getPayAmount() / Double.valueOf(attr.getValue())) / 100 + "";
					issue.setAmount(amountDiscount);
					issue.setLimitDeduct(amountDiscount);
				} else if ("name".equalsIgnoreCase(attr.getKeyName())) {
					issue.setName(attr.getValue());
				}
			});
			issue.setBatchNo(batchNo);
			issue.setSeqNo(order.getOrderNo());
			issue.setOrderNo(order.getOrderNo());
			issue.setVin(orderExtension.getCustomerVin());
			issue.setUseAmount("0.0");
			issue.setTargetDealer(orderExtension.getTargetDealerCode());
			issue.setUseDealer("0.0");
			issue.setLowestAmount("0.0");
			issue.setSendDmsStatus(OrderEnum.SEND_STATUS_0);
			issue.setSendDmsCount(0);
			issue.setCancel(OrderIssueEntity.CANCER_0);
			issue.setSendSmsStatus(OrderEnum.SEND_STATUS_0);
			issue.setCustomerMobile(order.getCustomer() != null ? order.getCustomer().getMobile() : "");
			issue.setOpenId(order.getCustomerOpenId());
			issue.setGoodsName(order.getGoodsName());
			order.setExtStatus(OrderEnum.EXT_STATUS_2);
			issueList.add(issue);
		});
		logger.info("下发DMS优惠券跑批任务 step second 修改订单已支付的extStatus为2......订单数量：{}，新增发送DMS数据量：{}", orderList.size(), issueList.size());
		return issueList;
	}


	private List<OrderIssueEntity> convertLotteryToDmsModel(List<LotteryRecordEntity> lotteryRecordList, String batchNo) {
		List<OrderIssueEntity> issueList = Lists.newLinkedList();
		lotteryRecordList.forEach(lotteryRecord -> {
			OrderIssueEntity issue = new OrderIssueEntity();
			OrderEntity order = lotteryRecord.getOrder();
			OrderExtensionEntity orderExtension = extensionService.findByOrderNo(order.getOrderNo());
			issue.setCampaignCode("GFB214/2017-3");
			issue.setName("双11活动刮奖赠券");
			issue.setValidBeginDate("2017-11-11");
			issue.setValidEndDate("2018-03-31");
			issue.setAmount(lotteryRecord.getDiscountMinusPrice() / 100 + "");
			issue.setLimitDeduct(lotteryRecord.getDiscountMinusPrice() / 100 + "");
			issue.setBatchNo(batchNo);
			issue.setSeqNo("L" + order.getOrderNo());
			issue.setOrderNo(order.getOrderNo());
			issue.setVin(orderExtension.getCustomerVin());
			issue.setUseAmount("0.0");
			issue.setTargetDealer(orderExtension.getTargetDealerCode());
			issue.setUseDealer("0.0");
			issue.setLowestAmount("0.0");
			issue.setSendDmsStatus(OrderEnum.SEND_STATUS_0);
			issue.setSendDmsCount(0);
			issue.setCancel(OrderIssueEntity.CANCER_0);
			issue.setSendSmsStatus(OrderEnum.SEND_STATUS_0);
			issue.setCustomerMobile(order.getCustomer() != null ? order.getCustomer().getMobile() : "");
			issue.setOpenId(order.getCustomerOpenId());
			issue.setGoodsName(order.getGoodsName());
			lotteryRecord.setExtStatus(OrderEnum.EXT_STATUS_2);
			issueList.add(issue);
		});
		logger.info("下发DMS优惠券跑批任务 step second 修改抽奖已支付的extStatus为2......抽奖数量：{}，新增发送DMS数据量：{}", lotteryRecordList.size(), issueList.size());
		return issueList;

	}

	private List<OrderIssueEntity> convertCrowResultToDmsModel(List<CrowResultEntity> crowResultList, String batchNo) {

		List<OrderIssueEntity> issueList = Lists.newLinkedList();
		crowResultList.forEach(crowResult -> {
			OrderIssueEntity issue = new OrderIssueEntity();
			OrderExtensionEntity orderExtension = extensionService.findByOrderNo(crowResult.getOrderNo());
			List<ActivityAttrEntity> activityAttrList = attrService.findBySn(crowResult.getActivityCode());
			logger.info(JSON.toJSONString(activityAttrList));
			activityAttrList.forEach(attr -> {
				if ("campaignCode".equalsIgnoreCase(attr.getKeyName())) {
					issue.setCampaignCode(attr.getValue());
				} else if ("validBeginDate".equalsIgnoreCase(attr.getKeyName())) {
					issue.setValidBeginDate(attr.getValue());
				} else if ("validEndDate".equalsIgnoreCase(attr.getKeyName())) {
					issue.setValidEndDate(attr.getValue());
				} else if ("name".equalsIgnoreCase(attr.getKeyName())) {
					issue.setName(attr.getValue());
				}else if("amount".equalsIgnoreCase(attr.getKeyName())){
					issue.setAmount(attr.getValue());
				}
			});
			issue.setBatchNo(batchNo);
			issue.setSeqNo(crowResult.getOrderNo());
			issue.setOrderNo(crowResult.getOrderNo());
			issue.setVin(orderExtension.getCustomerVin());
			issue.setUseAmount("0.0");
			issue.setTargetDealer(orderExtension.getTargetDealerCode());
			issue.setUseDealer("0.0");
			issue.setLowestAmount("0.0");
			issue.setSendDmsStatus(OrderEnum.SEND_STATUS_0);
			issue.setSendDmsCount(0);
			issue.setCancel(OrderIssueEntity.CANCER_0);
			issue.setSendSmsStatus(OrderEnum.SEND_STATUS_0);
			issue.setCustomerMobile(crowResult.getCustomerMobile());
			issue.setOpenId(crowResult.getOpenId());
			issue.setGoodsName(crowResult.getGoodsName());
			crowResult.setIssueDms(CrowResultEntity.ISSUE_DMS_3);
			issueList.add(issue);
		});
		logger.info("下发DMS众筹开奖结果跑批任务 step second 修改众筹开奖结果已支付的extStatus为2......订单数量：{}，新增发送DMS数据量：{}", crowResultList.size(), issueList.size());
		return issueList;
	}
}
